package com.example.goodpet.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.goodpet.bean.ResponseBody;
import com.example.goodpet.service.UserService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.Multipart;

/*
* 1.给用户友好的提示
* 2.当出现异常时把信息发送给后台，在后续解决bug
*
* */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static CrashHandler crashHandler=null;
    private Context mContext;
    //系统默认的出现未处理异常的处理器
    private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;
    //用来存储设备信息和异常信息
    private Map<String, String> infos = new HashMap<String, String>();

    //用于格式化日期,作为日志文件名的一部分
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    public static CrashHandler getInstance(){
        if (crashHandler==null)return new CrashHandler();
        else return  crashHandler;
    }
    private CrashHandler(){}
    public void init(Context context){
        this.mContext=context;
        defaultUncaughtExceptionHandler=Thread.getDefaultUncaughtExceptionHandler();
        //将处理器设置为当前处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {

        if (e==null){
            defaultUncaughtExceptionHandler.uncaughtException(t,e);
        }else{
            handleException(t,e);
        }
    }

    private void handleException(Thread t,Throwable e){
        //必须在主线程中执行Toast
        new Thread(){
            @Override
            public void run() {
                //Android系统当中，默认情况下，线程是没有开启looper消息处理的，但是主线程除外
                // prepare和loop中的内容就是在主线程中进行
                Looper.prepare();
                Toast.makeText(mContext, "亲，出现异常了！", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();
        //收集异常信息
        collectDeviceInfo(mContext);

        transferFile(saveCrashInfo2File(e));

        try {
            Thread.sleep(2000);
            //关闭资源，移除当前Activity
            ActivityManager.getInstance().removeCurrent();
            //结束当前进程
            android.os.Process.killProcess(android.os.Process.myPid());
            //结束虚拟机
            System.exit(0);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 收集设备参数信息
     * @param ctx
     */
    public void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("test", "an error occured when collect package info", e);
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
                //Log.d(TAG, field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e("test", "an error occured when collect crash info", e);
            }
        }
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return  返回文件名称,便于将文件传送到服务器
     */
    private String saveCrashInfo2File(Throwable ex) {

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result);
        try {
            long timestamp = System.currentTimeMillis();
            String time = formatter.format(new Date());
            String fileName = "crash-" + time + "-" + timestamp + ".log";
            File crash = mContext.getDir("crash", Context.MODE_PRIVATE);

                //File externalCacheDir = mContext.getExternalCacheDir();
            //System.out.println("CrashHandler.saveCrashInfo2File"+crash.getPath()+"/");
            String path=crash.getPath()+"/";
            FileOutputStream fos = new FileOutputStream(path + fileName);
            fos.write(sb.toString().getBytes());
            fos.close();
            return fileName;
        } catch (Exception e) {
            Log.e("test", "an error occured while writing file...", e);
        }
        return null;
    }


    private void transferFile(String filename) {
        UserService userService = RetrofitSingleton.getRetrofitNetConfig().create(UserService.class);
        File file1 = new File(mContext.getDir("crash", Context.MODE_PRIVATE)+"/"+filename);
        //System.out.println("CrashHandler.transferFile"+Environment.getExternalStorageDirectory().getPath()+filename);
        RequestBody file = RequestBody.create(MediaType.parse("multipart/form-data"), file1);

        MultipartBody.Part part = MultipartBody.Part.create(file);
        userService.uploadFile(part,filename).enqueue(new Callback<ResponseBody<String>>() {
            @Override
            public void onResponse(Call<ResponseBody<String>> call, Response<ResponseBody<String>> response) {
                //Log.d("test", "onResponse: ");
            }

            @Override
            public void onFailure(Call<ResponseBody<String>> call, Throwable t) {
                //Log.d("test", "onFailure: ");
            }
        });
    }
}

